package com.example.homework.db

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.example.homework.model.User

class UserDBHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
    companion object {
        private const val DB_NAME = "snake_db"
        private const val DB_VERSION = 1
        private const val TABLE_USER = "user"
    }

    private val CREATE_TABLE = "CREATE TABLE $TABLE_USER (" +
            "username TEXT PRIMARY KEY," +
            "high_score INTEGER DEFAULT 0)"

    override fun onCreate(db: SQLiteDatabase) {
        db.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        db.execSQL("DROP TABLE IF EXISTS $TABLE_USER")
        onCreate(db)
    }

    fun login(username: String): User {
        val db = readableDatabase
        val cursor = db.query(TABLE_USER, arrayOf("username", "high_score"),
            "username=?", arrayOf(username), null, null, null)

        return if (cursor.moveToFirst()) {
            val highScore = cursor.getInt(cursor.getColumnIndexOrThrow("high_score"))
            cursor.close()
            User(username, highScore)
        } else {
            val values = ContentValues().apply {
                put("username", username)
                put("high_score", 0)
            }
            db.insert(TABLE_USER, null, values)
            cursor.close()
            User(username, 0)
        }
    }

    fun updateHighScore(username: String, newScore: Int) {
        val db = writableDatabase
        val cursor = db.query(TABLE_USER, arrayOf("high_score"),
            "username=?", arrayOf(username), null, null, null)
        if (cursor.moveToFirst()) {
            val oldScore = cursor.getInt(0)
            if (newScore > oldScore) {
                val values = ContentValues().apply {
                    put("high_score", newScore)
                }
                db.update(TABLE_USER, values, "username=?", arrayOf(username))
            }
        }
        cursor.close()
    }
}